package com.juejin.www.controller;

import com.juejin.www.aspect.Log;
import com.juejin.www.aspect.Perm;
import com.juejin.www.model.DTO.CommentDTO;
import com.juejin.www.model.DTO.Result;
import com.juejin.www.model.VO.CommentVO;
import com.juejin.www.service.CommentService;
import com.juejin.www.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Jacky
 */
@Slf4j
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Log
    @Perm(permission = "comment:add")
    @PostMapping
    public Result add(@RequestBody CommentDTO commentDTO, @RequestHeader("token") String jwt){
        Integer uid = JwtUtils.getIdByJWT(jwt);
        commentDTO.setAuthorId(uid);
        if(commentDTO.getBeCommentedType()==1){
            log.info("{}用户评论{}号文章",commentDTO.getAuthorId(),commentDTO.getBeCommentedId());
        }else if(commentDTO.getBeCommentedType()==2){
            log.info("{}用户评论{}号沸点",commentDTO.getAuthorId(),commentDTO.getBeCommentedId());
        }else {
            log.info("{}用户回复{}号评论",commentDTO.getAuthorId(),commentDTO.getBeCommentedId());
        }
        commentService.add(commentDTO);
        return Result.success();
    }

    @Perm(permission = "comment:read")
    @GetMapping
    public Result getComments(@RequestParam Integer beCommentedId,Integer beCommentedType,@RequestHeader("token") String jwt){
        Integer uid = null;
        if(jwt!=null){
            try{
                uid = JwtUtils.getIdByJWT(jwt);
            }catch (Exception e){
                uid=null;
            }
        }
        log.info("获取评论");
        List<CommentVO> comments = commentService.getComments(beCommentedId, beCommentedType,uid);
        return Result.success(comments);
    }

    @Log
    @Perm(permission = "comment:delete")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        log.info("删除{}号评论",id);
        commentService.deleteComment(id);
        return Result.success();
    }
}
